<template>
    <div class="editorWrap">
        <div id="editorElem" style="text-align:left"></div>
        <div id="submit" :style="'height:' + submitHeight + 'px;line-height:' + submitHeight + 'px;'" v-on:click="getContent">提交</div>
    </div>
</template>

<script>
import E from 'wangeditor'

import axios from 'axios'
export default {
  name: 'Editor',
  props:{
    url:String
  },
  data() {
    return {
      editorContent: '',
      submitHeight: 30
    }
  },
   
  methods: {
    getContent: function() {
      this.$emit('getEditorData', this.editorContent)
    },
    clear:function (){
       editor.txt.clear()
    }
  },
  activated(){
    // const editor = new E('#editorElem')
    // editor.$txt.html('<p>a<br>a</p>');
    // this.clear();
  },
  mounted() {
    const editor = new E('#editorElem')
    
    editor.customConfig.onchange = (html) => {
      this.editorContent = html
    }
    // editor.customConfig.uploadImgShowBase64 = true   // 使用 base64 保存图片
    editor.customConfig.uploadImgServer = this.url  // 上传图片到服务器
    editor.customConfig.uploadFileName = 'contentImg[]';
    editor.customConfig.withCredentials = true
    editor.customConfig.debug =true
    let config = {
            headers: {
                'Content-Type': 'multipart/form-data'
            },  
        }
    let that = this
    editor.customConfig.customUploadImg = function (files, insert) {
        // files 是 input 中选中的文件列表
        // insert 是获取图片 url 后，插入到编辑器的方法
        let formData = new FormData() 
          for(var i=0;i<files.length ;i++){
            formData.append('file[]', files[i])
          }
        var url = that.url;
        axios.post( url,formData, config).then(function(result) {
          let imgUrls = result.data.data;
          for(var i=0;i<imgUrls.length;i++){
            insert(imgUrls[i])
                }
          formData.delete('file[]');
                        
        })
        
        

    }
    editor.customConfig.onchange = function (html) {
        // html 即变化之后的内容
        // console.log(html)
        that.$emit('getEditorData', html)
    }
    editor.create()
    editor.txt.clear()
    // console.log('editor')
    // console.log(document.getElementsByClassName('w-e-toolbar')[0])
    this.submitHeight = document.getElementsByClassName('w-e-toolbar')[0].offsetHeight
    // console.log(this.submitHeight)
  }
}
</script>

<style lang="stylus">
  .editorWrap {
    position: relative;
    #submit {
    position: absolute;
    top: 0;
    right: 0;
    width: 60px;
    text-align: center;
    cursor: pointer;
    }
    #submit:hover {
      color: #00b7ee;
    }
    .w-e-text-container {
      z-index: 200!important;
    }
  }
</style>